import pymysql
from sqlalchemy import create_engine

# 在这里设置你的MySQL密码
MYSQL_PASSWORD = "123456"  # 将这里替换为实际密码

def create_database():
    """创建数据库"""
    try:
        # 连接MySQL（使用你的密码）
        conn = pymysql.connect(
            host='localhost',
            user='root',
            password=MYSQL_PASSWORD,
            charset='utf8mb4'
        )
        
        # 创建数据库
        with conn.cursor() as cursor:
            cursor.execute("CREATE DATABASE IF NOT EXISTS stock_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
            print("✅ 数据库创建成功！")
        
        conn.commit()
        conn.close()
        
        # 创建表结构
        create_tables()
        
    except Exception as e:
        print(f"❌ 创建数据库时出错: {e}")

def create_tables():
    """创建数据表"""
    try:
        # 连接具体的数据库创建表
        engine = create_engine(f'mysql+pymysql://root:{MYSQL_PASSWORD}@localhost:3306/stock_db?charset=utf8mb4')
        
        from stock_spider.pipelines import Base
        Base.metadata.create_all(engine)
        print("✅ 数据表创建成功！")
        
    except Exception as e:
        print(f"❌ 创建表时出错: {e}")

if __name__ == '__main__':
    create_database()